﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;
//using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Drawing;

namespace 第六次作业
{
    public partial class MainForm : Form
    {
        private TreeView treeView;
        private ListView listView;
        private SplitContainer splitContainer;
        private ImageList imageList = new ImageList();

        public MainForm()
        {
            InitializeBasicForm();
            InitializeUI();
            LoadInitialDirectories();
        }

        private void InitializeBasicForm()
        {
            this.Size = new Size(1024, 768);
            this.Text = "文件浏览器";
            this.FormBorderStyle = FormBorderStyle.Sizable;
        }

        private void InitializeUI()
        {
            // 初始化ImageList
            imageList.Images.Add(SystemIcons.WinLogo);
            imageList.Images.Add(SystemIcons.Application);

            // 创建SplitContainer
            splitContainer = new SplitContainer();
            splitContainer.Dock = DockStyle.Fill;
            splitContainer.SplitterDistance = 250;
            this.Controls.Add(splitContainer);

            // 初始化TreeView
            treeView = new TreeView();
            treeView.Dock = DockStyle.Fill;
            treeView.ImageList = imageList;
            treeView.PathSeparator = "\\";
            treeView.BeforeExpand += TreeView_BeforeExpand;
            treeView.AfterSelect += TreeView_AfterSelect;
            splitContainer.Panel1.Controls.Add(treeView);

            // 初始化ListView
            listView = new ListView();
            listView.Dock = DockStyle.Fill;
            listView.View = View.Details;
            listView.Columns.Add("名称", 200);
            listView.Columns.Add("类型", 100);
            listView.Columns.Add("修改时间", 150);
            listView.DoubleClick += ListView_DoubleClick;
            splitContainer.Panel2.Controls.Add(listView);

            // 添加菜单
            var menuStrip = new MenuStrip();
            var fileMenu = new ToolStripMenuItem("文件(&F)");
            fileMenu.DropDownItems.Add("退出", null, (s, e) => Application.Exit());
            menuStrip.Items.Add(fileMenu);
            this.Controls.Add(menuStrip);
        }


        private void LoadInitialDirectories()
        {
            string userPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            TreeNode rootNode = new TreeNode("User")
            {
                ImageIndex = 0,
                SelectedImageIndex = 0,
                Tag = userPath
            };
            treeView.Nodes.Add(rootNode);
            LoadSubDirectories(rootNode);
        }

        private void LoadSubDirectories(TreeNode parentNode)
        {
            try
            {
                string path = parentNode.Tag.ToString();
                foreach (string directory in Directory.GetDirectories(path))
                {
                    TreeNode node = new TreeNode(Path.GetFileName(directory))
                    {
                        ImageIndex = 0,
                        SelectedImageIndex = 0,
                        Tag = directory
                    };
                    parentNode.Nodes.Add(node);
                }
            }
            catch { }
        }

        private void TreeView_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            foreach (TreeNode node in e.Node.Nodes)
            {
                if (node.Nodes.Count == 0)
                {
                    LoadSubDirectories(node);
                }
            }
        }

        private void TreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            listView.Items.Clear();
            string path = e.Node.Tag.ToString();

            try
            {
                foreach (string dir in Directory.GetDirectories(path))
                {
                    listView.Items.Add(new ListViewItem(new[] {
                        Path.GetFileName(dir),
                        "Folder",
                        Directory.GetLastWriteTime(dir).ToString()
                    })
                    { ImageIndex = 0 });
                }

                foreach (string file in Directory.GetFiles(path))
                {
                    listView.Items.Add(new ListViewItem(new[] {
                        Path.GetFileName(file),
                        "File",
                        File.GetLastWriteTime(file).ToString()
                    })
                    { ImageIndex = 1, Tag = file });
                }
            }
            catch { }
        }

        private void ListView_DoubleClick(object sender, EventArgs e)
        {
            if (listView.SelectedItems.Count > 0)
            {
                string path = listView.SelectedItems[0].Tag?.ToString();
                if (path != null && Path.GetExtension(path).ToLower() == ".xml")
                {
                    ShowXmlContent(path);
                }
            }
        }

        private void ShowXmlContent(string filePath)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);

                Form xmlViewer = new Form { Text = "XML Viewer - " + Path.GetFileName(filePath) };
                TreeView xmlTree = new TreeView { Dock = DockStyle.Fill };

                AddXmlNodes(xmlDoc.DocumentElement, xmlTree.Nodes);

                xmlViewer.Controls.Add(xmlTree);
                xmlViewer.Show();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error reading XML: {ex.Message}");
            }
        }

        private void AddXmlNodes(XmlNode xmlNode, TreeNodeCollection treeNodes)
        {
            TreeNode node = treeNodes.Add(xmlNode.Name);

            if (xmlNode.Attributes != null)
            {
                foreach (XmlAttribute attr in xmlNode.Attributes)
                {
                    node.Nodes.Add($"@{attr.Name} = {attr.Value}");
                }
            }

            if (!string.IsNullOrWhiteSpace(xmlNode.InnerText))
            {
                node.Nodes.Add($"Text: {xmlNode.InnerText.Trim()}");
            }

            foreach (XmlNode childNode in xmlNode.ChildNodes)
            {
                if (childNode.NodeType == XmlNodeType.Element)
                {
                    AddXmlNodes(childNode, node.Nodes);
                }
            }
        }



    }
}